package com.mindskip.xzs.controller.admin;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.github.pagehelper.PageInfo;
import com.mindskip.xzs.base.BaseApiController;
import com.mindskip.xzs.base.RestResponse;
import com.mindskip.xzs.base.SystemCode;
import com.mindskip.xzs.domain.Question;
import com.mindskip.xzs.domain.Subject;
import com.mindskip.xzs.domain.TextContent;
import com.mindskip.xzs.domain.enums.QuestionTypeEnum;
import com.mindskip.xzs.domain.question.QuestionObject;
import com.mindskip.xzs.service.QuestionService;
import com.mindskip.xzs.service.SubjectService;
import com.mindskip.xzs.service.TextContentService;
import com.mindskip.xzs.utility.*;
import com.mindskip.xzs.viewmodel.admin.question.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController("AdminQuestionController")
@RequestMapping(value = "/api/admin/question")
public class QuestionController extends BaseApiController {

    private final QuestionService questionService;
    private final TextContentService textContentService;
    private final SubjectService subjectService;

    @Autowired
    public QuestionController(QuestionService questionService, TextContentService textContentService,
            SubjectService subjectService) {
        this.questionService = questionService;
        this.textContentService = textContentService;
        this.subjectService = subjectService;
    }

    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public RestResponse<PageInfo<QuestionResponseVM>> pageList(@RequestBody QuestionPageRequestVM model) {
        PageInfo<Question> pageInfo = questionService.page(model);
        PageInfo<QuestionResponseVM> page = PageInfoHelper.copyMap(pageInfo, q -> {
            QuestionResponseVM vm = modelMapper.map(q, QuestionResponseVM.class);
            vm.setCreateTime(DateTimeUtil.dateFormat(q.getCreateTime()));
            vm.setScore(ExamUtil.scoreToVM(q.getScore()));
            TextContent textContent = textContentService.selectById(q.getInfoTextContentId());
            QuestionObject questionObject = JsonUtil.toJsonObject(textContent.getContent(), QuestionObject.class);
            String clearHtml = HtmlUtil.clear(questionObject.getTitleContent());
            vm.setShortTitle(clearHtml);
            return vm;
        });
        return RestResponse.ok(page);
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public RestResponse edit(@RequestBody @Valid QuestionEditRequestVM model) {
        RestResponse validQuestionEditRequestResult = validQuestionEditRequestVM(model);
        if (validQuestionEditRequestResult.getCode() != SystemCode.OK.getCode()) {
            return validQuestionEditRequestResult;
        }

        if (null == model.getId()) {
            questionService.insertFullQuestion(model, getCurrentUser().getId());
        } else {
            questionService.updateFullQuestion(model);
        }

        return RestResponse.ok();
    }

    @RequestMapping(value = "/select/{id}", method = RequestMethod.POST)
    public RestResponse<QuestionEditRequestVM> select(@PathVariable Integer id) {
        QuestionEditRequestVM newVM = questionService.getQuestionEditRequestVM(id);
        return RestResponse.ok(newVM);
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public RestResponse delete(@PathVariable Integer id) {
        Question question = questionService.selectById(id);
        question.setDeleted(true);
        questionService.updateByIdFilter(question);
        return RestResponse.ok();
    }

    private RestResponse validQuestionEditRequestVM(QuestionEditRequestVM model) {
        int qType = model.getQuestionType().intValue();
        boolean requireCorrect = qType == QuestionTypeEnum.SingleChoice.getCode()
                || qType == QuestionTypeEnum.TrueFalse.getCode();
        if (requireCorrect) {
            if (StringUtils.isBlank(model.getCorrect())) {
                String errorMsg = ErrorUtil.parameterErrorFormat("correct", "不能为空");
                return new RestResponse<>(SystemCode.ParameterValidError.getCode(), errorMsg);
            }
        }

        if (qType == QuestionTypeEnum.GapFilling.getCode()) {
            Integer fillSumScore = model.getItems().stream().mapToInt(d -> ExamUtil.scoreFromVM(d.getScore())).sum();
            Integer questionScore = ExamUtil.scoreFromVM(model.getScore());
            if (!fillSumScore.equals(questionScore)) {
                String errorMsg = ErrorUtil.parameterErrorFormat("score", "空分数和与题目总分不相等");
                return new RestResponse<>(SystemCode.ParameterValidError.getCode(), errorMsg);
            }
        }
        return RestResponse.ok();
    }

    @RequestMapping(value = "/generateByAI", method = RequestMethod.POST)
    public RestResponse<QuestionEditRequestVM> generateByAI(@RequestBody AIGenerateRequestVM model) {
        try {
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();

            // 根据题型构建不同的提示词
            String prompt = buildPromptByQuestionType(model);

            List<Map<String, String>> messageList = new ArrayList<>();
            Map<String, String> userMessage = new HashMap<>();
            userMessage.put("role", "user");
            userMessage.put("content", prompt);
            messageList.add(userMessage);

            requestBody.put("model", "qwen-plus");
            requestBody.put("messages", messageList);

            // 发送请求到AI服务
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + "sk-78bc57a7c914408abcd14ef11ca92a79");

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            RestTemplate restTemplate = new RestTemplate();

            ResponseEntity<Map> response = restTemplate.exchange(
                    "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
                    HttpMethod.POST,
                    entity,
                    Map.class);

            // 解析AI返回的结果
            Map<String, Object> responseBody = response.getBody();
            Map<String, Object> choices = ((List<Map<String, Object>>) responseBody.get("choices")).get(0);
            Map<String, Object> message = (Map<String, Object>) choices.get("message");
            String content = (String) message.get("content");

            // 将AI返回的内容转换为题目对象
            QuestionEditRequestVM questionVM = parseAIResponseToQuestion(content, model.getQuestionType());
            questionVM.setGradeLevel(model.getGradeLevel());
            questionVM.setSubjectId(model.getSubjectId());
            questionVM.setDifficult(model.getDifficult());

            return RestResponse.ok(questionVM);
        } catch (Exception e) {
            return RestResponse.fail(2, "AI生成题目失败：" + e.getMessage());
        }
    }

    /**
     * 根据题型构建不同的提示词
     */
    private String buildPromptByQuestionType(AIGenerateRequestVM model) {
        StringBuilder prompt = new StringBuilder();
        String questionTypeName = "";

        // 根据题型ID获取题型名称
        switch (model.getQuestionType()) {
            case 1:
                questionTypeName = "单选题";
                break;
            case 2:
                questionTypeName = "多选题";
                break;
            case 3:
                questionTypeName = "判断题";
                break;
            case 4:
                questionTypeName = "填空题";
                break;
            case 5:
                questionTypeName = "简答题";
                break;
            default:
                questionTypeName = "未知题型";
        }

        prompt.append("请你生成一道").append(questionTypeName).append("，");
        prompt.append("年级为").append(model.getGradeLevel()).append("级，");
        prompt.append("难度为").append(model.getDifficult()).append("（满分为5分）。");

        // 添加学科信息
        if (model.getSubjectId() != null) {
            Subject subject = subjectService.selectById(model.getSubjectId());
            if (subject != null) {
                prompt.append("学科为").append(subject.getName()).append("，");
            }
        }

        if (StringUtils.isNotBlank(model.getKnowledgePoint())) {
            prompt.append("知识点为：").append(model.getKnowledgePoint()).append("。");
        }

        // 根据不同题型添加特定要求
        switch (model.getQuestionType()) {
            case 1: // 单选题
                prompt.append("请生成一道单选题，包含题干、4个选项（A、B、C、D）、正确答案（只有一个）和解析。");
                prompt.append(
                        "返回格式为JSON：{\"title\":\"题干\", \"items\":[{\"prefix\":\"A\", \"content\":\"选项A内容\"}, ...], \"correct\":\"正确选项前缀\", \"analyze\":\"解析\", \"score\":分数, \"difficult\":难度}");
                break;
            case 2: // 多选题
                prompt.append("请生成一道多选题，包含题干、4个选项（A、B、C、D）、正确答案（多个）和解析。");
                prompt.append(
                        "返回格式为JSON：{\"title\":\"题干\", \"items\":[{\"prefix\":\"A\", \"content\":\"选项A内容\"}, ...], \"correctArray\":[\"正确选项前缀1\", \"正确选项前缀2\", ...], \"analyze\":\"解析\", \"score\":分数, \"difficult\":难度}");
                break;
            case 3: // 判断题
                prompt.append("请生成一道判断题，包含题干、选项（A:正确，B:错误）、正确答案和解析。");
                prompt.append(
                        "返回格式为JSON：{\"title\":\"题干\", \"items\":[{\"prefix\":\"A\", \"content\":\"正确\"}, {\"prefix\":\"B\", \"content\":\"错误\"}], \"correct\":\"正确选项前缀\", \"analyze\":\"解析\", \"score\":分数, \"difficult\":难度}");
                break;
            case 4: // 填空题
                prompt.append("请生成一道填空题，包含题干（用下划线表示填空处）、填空答案和解析。");
                prompt.append(
                        "返回格式为JSON：{\"title\":\"题干\", \"items\":[{\"prefix\":\"1\", \"content\":\"填空1答案\", \"score\":分数}, ...], \"analyze\":\"解析\", \"score\":总分数, \"difficult\":难度}");
                break;
            case 5: // 简答题
                prompt.append("请生成一道简答题，包含题干、参考答案和解析。");
                prompt.append(
                        "返回格式为JSON：{\"title\":\"题干\", \"correct\":\"参考答案\", \"analyze\":\"解析\", \"score\":分数, \"difficult\":难度}");
                break;
        }

        return prompt.toString();
    }

    /**
     * 将AI返回的内容解析为题目对象
     */
    private QuestionEditRequestVM parseAIResponseToQuestion(String content, Integer questionType) {
        try {
            // 提取JSON内容
            int startIndex = content.indexOf("{");
            int endIndex = content.lastIndexOf("}") + 1;
            if (startIndex >= 0 && endIndex > startIndex) {
                content = content.substring(startIndex, endIndex);
            }

            // 解析JSON
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> map = objectMapper.readValue(content, Map.class);

            QuestionEditRequestVM questionVM = new QuestionEditRequestVM();
            questionVM.setQuestionType(questionType);
            questionVM.setTitle((String) map.get("title"));
            questionVM.setAnalyze((String) map.get("analyze"));

            // 设置分数
            Object scoreObj = map.get("score");
            if (scoreObj instanceof Integer) {
                questionVM.setScore(String.valueOf(((Integer) scoreObj).floatValue()));
            } else if (scoreObj instanceof Double) {
                questionVM.setScore(String.valueOf(((Double) scoreObj).floatValue()));
            } else if (scoreObj instanceof String) {
                questionVM.setScore(String.valueOf(Float.parseFloat((String) scoreObj)));
            }

            // 设置难度
            Object difficultObj = map.get("difficult");
            if (difficultObj instanceof Integer) {
                questionVM.setDifficult((Integer) difficultObj);
            } else if (difficultObj instanceof Double) {
                questionVM.setDifficult(((Double) difficultObj).intValue());
            } else if (difficultObj instanceof String) {
                questionVM.setDifficult(Integer.parseInt((String) difficultObj));
            }

            // 根据题型设置特定字段
            switch (questionType) {
                case 1: // 单选题
                    questionVM.setCorrect((String) map.get("correct"));
                    questionVM.setItems(objectMapper.convertValue(map.get("items"),
                            new TypeReference<List<QuestionEditItemVM>>() {
                            }));
                    break;
                case 2: // 多选题
                    questionVM.setCorrectArray(objectMapper.convertValue(map.get("correctArray"),
                            new TypeReference<List<String>>() {
                            }));
                    questionVM.setItems(objectMapper.convertValue(map.get("items"),
                            new TypeReference<List<QuestionEditItemVM>>() {
                            }));
                    break;
                case 3: // 判断题
                    questionVM.setCorrect((String) map.get("correct"));
                    questionVM.setItems(objectMapper.convertValue(map.get("items"),
                            new TypeReference<List<QuestionEditItemVM>>() {
                            }));
                    break;
                case 4: // 填空题
                    questionVM.setItems(objectMapper.convertValue(map.get("items"),
                            new TypeReference<List<QuestionEditItemVM>>() {
                            }));
                    break;
                case 5: // 简答题
                    questionVM.setCorrect((String) map.get("correct"));
                    break;
            }

            return questionVM;
        } catch (Exception e) {
            throw new RuntimeException("解析AI返回内容失败: " + e.getMessage());
        }
    }
}
